package com.dexilaonian.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dexilaonian.MainActivity;
import com.dexilaonian.R;
import com.dexilaonian.model.AddressPickTask;
import com.dexilaonian.permission.AfterPermissionGranted;
import com.dexilaonian.permission.PermissionUtils;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.BitmapZip;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.FileUtils;
import com.dexilaonian.utils.ImageLoader;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PreferencesUtil;
import com.dexilaonian.view.DatePickerPopWin;
import com.dexilaonian.view.MultiImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import bakerj.backgrounddarkpopupwindow.BackgroundDarkPopupWindow;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import okhttp3.Call;

public class UserActivity extends BaseActivity implements View.OnClickListener {
    private static final int CAMERA_PERIMISSION_CODE = 0;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.tv_userName)
    TextView tvUserName;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.user_go1)
    ImageView userGo1;
    @Bind(R.id.tv_data)
    TextView tvData;
    @Bind(R.id.user_go2)
    ImageView userGo2;
    @Bind(R.id.user_go4)
    ImageView userGo4;
    @Bind(R.id.user_btn)
    Button userBtn;
    @Bind(R.id.rl_gender)
    RelativeLayout rlGender;
    @Bind(R.id.rl_birthday)
    RelativeLayout rlBirthday;
    private static final String IMAGE_FILE_NAME = "avatarImage.jpg";// 头像文件名称
    @Bind(R.id.iv_head2)
    ImageView ivHead2;
    @Bind(R.id.tv_province)
    TextView tv_province;
    @Bind(R.id.ll_select_province)
    RelativeLayout ll_select_province;
    @Bind(R.id.mainLayout)
    RelativeLayout mainLayout;
    @Bind(R.id.user_iv)
    ImageView userIv;
    private String user_url = Constant.base_url + "/user/getMyInfoDetail.do";
    private String edit_url = Constant.base_url + "/user/editMyInfo.do";
    private long startDay = 0;
    private int count;
    private BackgroundDarkPopupWindow window;
    private String imageUrl;
    private String name;
    private String phone;
    private String face;
    private String birthday;
    private String province;
    private int gender;
    private String city;
    private String dateDesc;
    private String myprovice;
    private String mycity1;
    private String provinceStr;
    private String cityStr;
    private String countyStr;

    @Override
    public int getLayoutID() {
        return R.layout.activity_user;
    }

    @Override
    public void initView() {
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
    }
//获取性别
    private void initClick() {
        rlGender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopwindow_gender();
            }
        });

        rlBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initBirth();
            }
        });

        ll_select_province.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wheel();
            }
        });

        userBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initBtn();
            }
        });
        ivHead2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initCamera();
            }
        });
    }


    private void initCamera() {
        String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (PermissionUtils.hasPermissions(UserActivity.this, perms)) {
            startPickPicActivity();
        } else {
            PermissionUtils.requestPermissions(UserActivity.this, "需要拍照和相册权限", CAMERA_PERIMISSION_CODE, perms);
            initCamera();
        }
    }

    private void init() {
        Map<String, String> map = new HashMap<>();
        Okhttp.postString(true, user_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(UserActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        String data = jsonObject.optString("data");
                        if (!TextUtils.isEmpty(data)) {
                            JSONObject object = new JSONObject(data);
                            name = object.optString("name");
                            phone = object.optString("phone");
                            face = object.optString("face");
                            birthday = object.optString("birthday");
                            province = object.optString("province");
                            gender = Integer.parseInt(object.optString("gender"));
                            city = object.optString("city");
                            if (name != null) {
                                tvUserName.setText(name);
                            } else {
                                tvUserName.setText("");
                            }
                            if (!TextUtils.isEmpty(phone)) {
                                tvPhone.setText(phone);
                            }
                            if (!TextUtils.isEmpty(birthday)) {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                String format = simpleDateFormat.format(new Date(Long.parseLong(String.valueOf(birthday))));
                                tvData.setText(format);
                            }
                            if (gender == 1) {
                                tvSex.setText("男");
                            } else {
                                tvSex.setText("女");
                            }
                            if (TextUtils.isEmpty(city) || TextUtils.isEmpty(province)) {
                            } else {
                                tv_province.setText(province + " " + city);
                            }
                            if (TextUtils.isEmpty(face)) {
                                ivHead2.setImageResource(R.drawable.user);
                            } else {
                                ImageLoader.displayCircle(UserActivity.this, face, ivHead2);
                                new DownloadImageTask().execute(face);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {

            }
        });
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {
            userIv.setBackgroundDrawable(result);
        }
    }

    private Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过第二个参数(文件名)来判断，是否本地有此图片
            drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);
        } catch (IOException e) {
            Log.e("skythinking", e.getMessage());
        }

        return drawable;
    }

    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

        }
    }

    private ArrayList<String> mSelectPath = new ArrayList<>();

    @AfterPermissionGranted(CAMERA_PERIMISSION_CODE)
    public void startPickPicActivity() {
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        //selectedMode = MultiImageSelectorActivity.MODE_SINGLE;
        boolean showCamera = true;
        int maxNum = 1;
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, showCamera);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }
    private static final int REQUEST_IMAGE = 2;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    postFile(new File(mSelectPath.get(i)));
                }
            }
        }
    }

    /**
     * 上传文件
     */
    private void postFile(File file) {
        final String pic_path = file.getPath();
        String targetPath = FileUtils.getSDCardPath() + file.getName();
        //压缩图片的方法
        final String compressImage = BitmapZip.compressImage(pic_path, targetPath, 90);
        final File compressedPic = new File(compressImage);
        if (compressedPic.exists()) {
            file = compressedPic;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        showProgressBar(true);
        String url = Constant.base_url + "/upload/image";
        Okhttp.postFileParams(url, file, params, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(e.getMessage());
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showToast(response);
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String content = jsonObject.optString("data");
                    JSONObject content_json = new JSONObject(content);
                    String face = content_json.optString("path");
                    if (!TextUtils.isEmpty(face)) {
                        imageUrl = Constant.base_pic_url + face;
                        ImageLoader.displayCircle(UserActivity.this, imageUrl, ivHead2);
                        new DownloadImageTask().execute(imageUrl);
                        PreferencesUtil.putString(UserActivity.this, Constant.IMAGE, imageUrl);
                        showToast("头像上传成功");
                    } else {
                        showToast("头像上传失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });
    }

    /**
     * 弹出选择器
     */
    private void wheel() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);

        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                showToast("数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                provinceStr = province.getAreaName();
                cityStr = city.getAreaName();
                countyStr = county.getAreaName();
                tv_province.setText(provinceStr + " " + cityStr + " " + countyStr);
            }
        });
        task.execute("广东 ", "深圳 ", "福田");

    }

    private void initBirth() {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(UserActivity.this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                tvData.setText(dateDesc);
                UserActivity.this.dateDesc = dateDesc;

            }
        }).textConfirm("确定") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#009900"))//color of confirm button
                .minYear(1900) //min year in loop
                .maxYear(2550) // max year in loop
                .dateChose("2013-11-11") // date chose when init popwindow
                .build();
        pickerPopWin.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        pickerPopWin.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        pickerPopWin.showPopWin(UserActivity.this);
    }

    /**
     * 显示popupWindow
     */
    private void showPopwindow_gender() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popwindowlayout_gender, null);
        TextView man = (TextView) view.findViewById(R.id.man);
        TextView woman = (TextView) view.findViewById(R.id.woman);
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()

        window = new BackgroundDarkPopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                500);
        window.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window.setDarkStyle(-1);
        window.resetDarkPosition();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        window.setBackgroundDrawable(getResources().getDrawable(R.color.colorpopuwindow));
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(UserActivity.this.findViewById(R.id.tv_phone),
                Gravity.BOTTOM, 0, 0);
        man.setOnClickListener(this);
        woman.setOnClickListener(this);
        //  window.showAsDropDown(nextNew, Gravity.BOTTOM, 0, 0);
        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    private void initBtn() {
        showProgressBar(true);
        String tvUsername = tvUserName.getText().toString().trim();
        String tvphone = tvPhone.getText().toString().trim();
        String sex = tvSex.getText().toString().trim();
        String tvdata = tvData.getText().toString().trim();//生日
        String address = tv_province.getText().toString().trim();
        if (TextUtils.isEmpty(tvdata)) {
            showToast("请选择时间");
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date parse = formatter.parse(tvdata);
            long time = parse.getTime();
            startDay = Math.abs(time);
            Log.e("TTT时间戳", startDay + "");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(address)) {
            String[] split = address.split(" ");
            myprovice = split[0];
            mycity1 = split[1];
        }

        if (sex.equals("男")) {
            count = 1;
        } else {
            count = 2;
        }
        if (TextUtils.isEmpty(imageUrl)) {
            imageUrl = PreferencesUtil.getString(UserActivity.this, Constant.IMAGE);
        }
        Map<String, String> map = new HashMap<>();
        map.put("name", tvUsername);
        map.put("faceUrl", imageUrl);
        map.put("birthday", startDay + "");
        map.put("city", mycity1);
        map.put("province", myprovice);
        map.put("gender", count + "");
        Okhttp.postString(true, edit_url, map, new Okhttp.CallBac() {
            private int status;

            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject json = new JSONObject(response);
                    status = Integer.parseInt(json.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(UserActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 18) {
                        showToast("系统错误");
                    }
                    if (status == 0) {
                        showToast("修改成功");
                        Intent intent = new Intent(UserActivity.this, MainActivity.class);
                        intent.putExtra("user", 1);
                        startActivity(intent);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.woman:
                tvSex.setText("女");
                window.dismiss();
                break;
            case R.id.man:
                tvSex.setText("男");
                window.dismiss();
                break;
        }
    }
}

